<?php
namespace app\index\model;
use think\Db;
class User{
    /**
     * 判断是否登录
     * 如果有cookie值， 则自动登录
     * @return true or false
     */
    public function isLogin(){
        $token = cookie('token');
        $ip    = com_client_ip();
        $rs = Db::query("select * from user where token!='' and token=? and last_login_ip=?",[$token,$ip]);
        if( !$rs ){
            return false;
        }
        return $rs[0];
    }
    /**
     * 用户登录
     * @param unknown $user_no 用户名
     * @param unknown $pwd 密码
     * @return true or false
     */
    public function logIn($user_no, $pwd){
        $rs = Db::name('user')->where('user_no', $user_no)->find();
        //判断
        if(!$rs)
            return com_error('用户编号不存在！','user_no');
        if( com_password($pwd) != $rs['pwd'])
            return com_error('密码错误！','pwd');

        $token = com_token($rs['id']);
        cookie('token',$token);
        $ip    = com_client_ip();
        $time  = time();
        $data = [
            "id"              => $rs['id'],
            "last_login_time" => $time,
            "last_login_ip"   => $ip,
            "login_times"     => $rs['login_times']+1,
            "error_times"     => 0,
            "token"           => $token,
        ];
        Db::name("user")->update($data);
        Db::name("login_history")->insert([
          'type' => 0,
          'user_id' => $rs['id'],
          'login_time' => $time,
          'login_ip' => $ip,
        ]);
        return true;
    }
    /**
     * 退出登录
     * 清楚cookie和session
     */
    public function logOut(){
        $token = cookie("token");
        Db::name("user")->where("token",$token)->update(['token'=>'']);
        cookie("token",null);
    }
}
